package test.android;

import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.app.Dialog;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

public class Utils {
	public static boolean checkInternet(Context c) {
		ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
		android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		if (wifi.isConnected() || mobile.isConnected()) return true;
		else return false;
	}
	
	public static void toast(Context context, String message) {
		Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
	}
	
	public static void checkInternetAndToast(Context c) {
		if (checkInternet(c))
			toast(c, "Download error");
		else 
			toast(c, "Can not connect.Check internet");
	}
	
	public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		MessageDigest md;
		md = MessageDigest.getInstance("MD5");
		byte[] md5hash = new byte[32];
		md.update(text.getBytes("iso-8859-1"), 0, text.length());
		md5hash = md.digest();
		return convertToHex(md5hash);
	}

	private static String convertToHex(byte[] data) {
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < data.length; i++) {
			int halfbyte = (data[i] >>> 4) & 0x0F;
			int two_halfs = 0;
			do {
				if ((0 <= halfbyte) && (halfbyte <= 9))
					buf.append((char) ('0' + halfbyte));
				else
					buf.append((char) ('a' + (halfbyte - 10)));
				halfbyte = data[i] & 0x0F;
			} while (two_halfs++ < 1);
		}
		return buf.toString();
	}	
	
	public static void toggleSoftKeyboard(Context context) {
		InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, 0);
	}
	
	public static File resizeBitmap(File inputFile, int requiredWidth) {
		// create resized bitmap
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(inputFile.getPath(), options);
		Log.e("stk", "original size=" + options.outWidth + "x" + options.outHeight);
		options.inSampleSize = (int) Math.floor(options.outWidth * 1.0 / requiredWidth);
		Log.e("stk", "sampled size=" + options.inSampleSize);
		
		if (options.inSampleSize <= 1) {
			return inputFile;
		}
		
		options.inJustDecodeBounds = false;
		Bitmap resizedBitmap = BitmapFactory.decodeFile(inputFile.getPath(), options);
		Log.e("stk", "resized size=" + options.outWidth + "x" + options.outHeight);
		
		try {
			// create file containing resized bitmap
			File file = new File(inputFile.getParent(), inputFile.getName() + "_resized_" + requiredWidth);
			FileOutputStream fos = new FileOutputStream(file);
			resizedBitmap.compress(CompressFormat.PNG, 90, fos);
			resizedBitmap.recycle();
			return file;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}	
	
	public static Bitmap resizeBitmap(String filePath, int requiredWidth) {
		// create resized bitmap
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, options);
		options.inSampleSize = (int) Math.floor(options.outWidth * 1.0 / requiredWidth);
		if (options.inSampleSize <= 1) {
			return BitmapFactory.decodeFile(filePath);
		}
		Log.e("stk", "sampleSize=" + options.inSampleSize);
		options.inJustDecodeBounds = false;
		Bitmap resizedBitmap = BitmapFactory.decodeFile(filePath, options);
		return resizedBitmap;
	}
	
	public static File saveBitmapToFile(Bitmap bitmap, String filePath) {
		try {
			File file = new File(filePath);
			FileOutputStream fos = new FileOutputStream(file);
			bitmap.compress(CompressFormat.JPEG, 90, fos);
			return file;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}
	
	public static int getCameraPhotoOrientation(Context context, Uri imageUri, String imagePath) {
		int rotate = 0;
		try {
			context.getContentResolver().notifyChange(imageUri, null);
			File imageFile = new File(imagePath);
			ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
			int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_270:
				rotate = 270;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				rotate = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_90:
				rotate = 90;
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		Log.e("stk", "rotate=" + rotate);
		return rotate;
	}  	
	
	public static String[] getContactsEmail(Context c) {
		// Run query
		Uri uri = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
		String[] projection = new String[] {ContactsContract.CommonDataKinds.Email.DATA };
		String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + "='1'";
		String[] selectionArgs = null;
		String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
		
		Cursor cursor = c.getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
		String[] listEmails = new String[cursor.getCount()];
		
		for (int i = 0; i < cursor.getCount(); i++) {
			cursor.moveToPosition(i);
			listEmails[i] = cursor.getString(0);
		}
		
		cursor.close();
		return listEmails;
	}		
	
}
